package cn.edu.jxau.test;

import java.util.ArrayList;
import java.util.List;

/**
 * 有向图
 * @author 付大石
 */
public class DirectedGraph {
    
    public static void main(String[] args) {
        
        DirectedGraph g = new DirectedGraph(8);
        g.addEdge(new DirectedEdge(4,5,0.35));
        g.addEdge(new DirectedEdge(5,4,0.35));
        g.addEdge(new DirectedEdge(4,7,0.37));
        g.addEdge(new DirectedEdge(5,7,0.28));
        g.addEdge(new DirectedEdge(7,5,0.28));
        g.addEdge(new DirectedEdge(5,1,0.32));
        g.addEdge(new DirectedEdge(0,4,0.38));
        g.addEdge(new DirectedEdge(0,2,0.26));
        g.addEdge(new DirectedEdge(7,3,0.39));
        g.addEdge(new DirectedEdge(1,3,0.29));
        g.addEdge(new DirectedEdge(2,7,0.34));
        g.addEdge(new DirectedEdge(6,2,0.40));
        g.addEdge(new DirectedEdge(3,6,0.52));
        g.addEdge(new DirectedEdge(6,0,0.58));
        g.addEdge(new DirectedEdge(6,4,0.93));
        System.out.println(g);
    }
    
    /**
     * 顶点数
     */
    private int v;

    /**
     * 边数
     */
    private int e;

    /**
     * 邻接表
     */
    private List<DirectedEdge>[] adj;

    public DirectedGraph(int v) {

        this.v = v;
        adj = new List[v];
        for (int i = 0; i < adj.length; i++) {
            adj[i] = new ArrayList<>();
        }
    }

    public int v() {
        return v;
    }

    public int e() {
        return e;
    }

    /**
     * 增加一条有向边
     * @param edge
     */
    public void addEdge(DirectedEdge edge) {
        adj[edge.from()].add(edge);
        e++;
    }

    public Iterable<DirectedEdge> adj(int v) {
        return adj[v];
    }

    public Iterable<DirectedEdge> edges() {

        List<DirectedEdge> list = new ArrayList<>();
        for (int i = 0; i < adj.length; i++) {
            for (DirectedEdge edge : adj[i]) {
                list.add(edge);
            }
        }
        return list;
    }

    @Override
    public String toString() {

        StringBuilder builder = new StringBuilder();
        builder.append("v:").append(v).append("\t").append("e:").append(e).append("\n");
        for (int i = 0; i < adj.length; i++) {
            builder.append(i).append(":\t");
            for (DirectedEdge edge : adj(i)) {
                builder.append(edge.to()).append("(").append(edge.weight()).append(")").append("\t");
            }
            builder.append("\n");
        }
        builder.deleteCharAt(builder.length()-1);
        return builder.toString();
    }
}
